// 用户相关

import { removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
import { setToken as setLoToken, getToken } from "@/utils";
import { loginApi, getProfile } from '@/apis/user'
const userStore = createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  //同步修改
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      setLoToken(action.payload)
    },
    setUser(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  },
})
// 异步方法
function fetchLogin(loginFrom) {
  return async (dispatch) => {
    // 发送异步请求
    const res = await loginApi(loginFrom)
    // 提交同步action进行token的存入
    if (res.data) {
      dispatch(setToken(res.data.token))
    }
  }
}

// 个人用户信息 异步方法
function fetchUserInfo() {
  return async (dispatch) => {
    // 发送异步请求
    const res = await getProfile()
    // 提交同步action进行userInfo的存入
    if (res.data) {
      dispatch(setUser(res.data))
    }
  }
}
// 解构actionCreater
const { setToken, setUser, clearUserInfo } = userStore.actions

// 获取reducer
const userReducers = userStore.reducer

export {
  setToken,
  fetchLogin,
  fetchUserInfo,
  clearUserInfo
}
export default userReducers